<?php 

/**
 * Base class for all Modules to be developed for the CMS
 */
abstract class Module extends Controller {

	protected $layout = "cms_layout.php";
	protected $template = "index.php";
	protected $db = NULL;
	
	public function __construct($basedir = NULL) {

		$this->db = new Database();
        
        // initiate the models as class variables
        if( $this->models != NULL ) {
			if( $basedir == NULL ) {
				$basedir = CORE_PATH;	
			}
			
            foreach($this->models as $model) {
				$modelPath = $basedir . "/models/" . $model . ".php";
                
                if( file_exists($modelPath) && !class_exists($model) ) {
					include_once($modelPath);
					
                    $this->{$model} = new $model();
                }
				
				else if( class_exists($model) ) {
					$this->{$model}	= new $model();
				}
            }
        }
		
		// initiate the helper classes available for use by this Controller
		if( $this->helpers != NULL ) {
            foreach($this->helpers as $helper_name) {
                if( class_exists($helper_name) && is_subclass_of($helper_name, 'Helper') ) {
                    $this->{$helper_name} = new $helper_name($this);
                }
            }
        }
        
        // initiate the view instance
        if( $this->view == NULL ) {
            $this->view = new View($this, $this->layout);
        }
	}

	public function index() {
        
    }
	
	public function beforeFilter() {
			
	}
    
    public function fireAction($actionName, $params = array()) {
        
		// call any pre action function
		$this->beforeFilter();

		// filter and call the function
        call_user_func_array(array($this,$actionName), $params);
        
        if( $this->autoRender ) {
            $view = new ModuleView($this, $this->layout);
            $view->render($actionName);
        }
		
		// call post action function
		$this->afterFilter();
    }
	
	public function afterFilter() {
		
	}
	
	public function beforeRender() {
		
	}

    /**
     * Renders the contents of the Controller to the view
     */
    public function render() {
	
		// call any callbacks defined
		$this->beforeRender();
		
		// render the view
		$view = new ModuleView($this, $this->layout);
		$view->render();
		
		// call any callbacks defined
		$this->afterRender();
    }
    
    public function afterRender() {
		
	}
	
	public function redirect($params = array()) {
		
		$path = Router::url( get_class($this), $params);
		
		header("Location: $path");
	}
}
?>